/**
 * reduce 去重
 * @param {Array<string | number>} arr
 */
export const dedupReduce = (arr: Array<string | number>) => {
	return arr.reduce(
		(prev, cur) => {
			if (prev.indexOf(cur) === -1) {
				prev.push(cur)
			}
			return prev
		},
		[arr[0]]
	)
}

/**
 * indexof 去重
 * @param {Array<string | number>} arr
 */
export function arrDedup(arr: Array<string | number>) {
	const res = [] as Array<string | number>
	arr.forEach((item) => {
		if (res.indexOf(item) < 0) {
			res.push(item)
		}
	})
	return res
}

/**
 * 冒泡 去重
 * @param {Array<string | number>} arr
 */
export function dedup(arr = []) {
	const t = []
	t[0] = arr[0] // 让新数组有长度
	for (let i = 0; i < arr.length; i++) {
		for (let k = 0; k < t.length; k++) {
			if (t[k] === arr[i]) {
				break
			}
			if (k === t.length - 1) {
				t.push(arr[i]) // 拿到原数组某个元素比较到新数组中的最后一个元素没有重复
			}
		}
	}
	return t
}

/**
 * 去重
 * @param {Array<string | number>} arr
 * @returns {Array<string | number>}
 */
export const unique = (arr) => {
	return [...new Set(arr)]
}

/**
 * 交集
 * @param {Array<string | number>} arr1
 * @param {Array<string | number>} arr2
 */
export const calcInterMap = (arr1: Array<string | number>, arr2: Array<string | number>) => {
	const map = new Map()
	const res = [] as Array<string | number>
	arr1.forEach((n) => {
		map.set(n, true)
	})
	arr2.forEach((n) => {
		if (map.get(n)) {
			res.push(n)
			map.delete(n)
		}
	})
	return res
}

/**
 * 交集
 * @param {Array<string | number>} arr1
 * @param {Array<string | number>} arr2
 * @returns {Array<string | number>}
 */
export const intersection = (arr1, arr2) => {
	return [...new Set(arr1)].filter((item) => new Set(arr2).has(item))
}

/**
 * 差集
 * @param {Array<string | number>} arr1
 * @param {Array<string | number>} arr2
 * @returns {Array<string | number>}
 */
export const difference = (arr1, arr2) => {
	return [...new Set(arr1)].filter((item) => !new Set(arr2).has(item))
}

/**
 * 并集
 * @param {Array<string | number>} arr1
 * @param {Array<string | number>} arr2
 * @returns {Array<string | number>}
 */
export const union = (arr1, arr2) => {
	return [...new Set([...arr1, ...arr2])]
}

/**
 * @description: 冒泡排序
 * @param {number[]} array
 */
export function bubbleSort(array) {
	const arr = array
	for (let i = 0; i < arr.length - 1; i++) {
		for (let j = 0; j < arr.length - 1; j++) {
			if (arr[j] > arr[j + 1]) {
				const temp = arr[j]
				arr[j] = arr[j + 1]
				arr[j + 1] = temp
			}
		}
	}
	return arr
}
